<template>
  <div class="list-pages white-bg">
    <div class="search-form-box">
      <a-form :model="formState" name="horizontal_login" :label-col="labelCol" autocomplete="off" @finish="onFinish">
        <a-row :gutter="[16, 16]">
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="姓名" name="name">
              <a-input v-model:value="formState.name" placeholder="请输入">
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="账号" name="login_name">
              <a-input v-model:value="formState.login_name" placeholder="请输入">
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="处理状态" name="feedback_status_id">
              <a-select v-model:value="formState.feedback_status_id" placeholder="请选择" allowClear>
                <a-select-option :value=1>已处理</a-select-option>
                <a-select-option :value=0>未处理</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="问题分类" name="feedback_category_idArray">
              <a-select v-model:value="formState.feedback_category_idArray" placeholder="请选择" mode="multiple"
                allowClear>

                <a-select-option v-for="option in classOptions" :key="option.value" :value="option.value">
                  {{ option.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="9" :xl="9" v-show="expand">
            <a-form-item label="反馈时间" name="createTime">
              <a-range-picker v-model:value="formState.createTime" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6">
            <a-form-item>
              <div class="search-btn-box" :class="{ pt: expand }">
                <a-button :icon="h(SearchOutlined)" type="primary" html-type="submit" class="search-btn">查询</a-button>
                <a-button :icon="h(ReloadOutlined)" class="reset-btn" @click="resetForm">清空</a-button>
                <a class="expand-btn" style="font-size: 12px; margin-left: 12px" @click="expand = !expand">
                  <template v-if="expand">
                    <UpOutlined />
                  </template>
                  <template v-else>
                    <DownOutlined />
                  </template>
                  {{ expand ? "收起查询" : "展开查询" }}
                </a>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="opt-button-box">
      <a-button class="btn" @click="handleExport">
        <img src="/icons/common/icon-export.png" class="icon" />
        导出反馈
      </a-button>
      <!-- <a-upload :show-upload-list="false" :before-upload="handleImport" accept=".xlsx,.xls">
        <a-button class="btn" style="margin-left: 12px;">
          <img src="/icons/common/icon-import.png" class="icon" />
          导入反馈
        </a-button>
      </a-upload> -->
    </div>
    <div class="table-wrapper" ref="tableRef">
      <a-table class="table-box" row-key="index" :columns="columns" :dataSource="tableData" :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)
        " sticky :scroll="{ y: true, x: 1100 }" :pagination="pagination" @change="onChange">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex == 'files'">
            <div v-for="option in record.files" :key="option.fileId">
              <a :href="option.url" target="_blank">{{ option.file_name }}</a>
            </div>
          </template>
          <template v-if="column.dataIndex == 'feedback_category_id'">
            <!-- <div class="cell-status-box" :class="{ 'is-active': record.feedback_status_id === 1 }">
              <div class="status-dot"></div>
              <div class="status-text">
                {{ record.feedback_status_id === 1 ? "已完成" : "未完成" }}
              </div>
            </div> -->
            <template v-for="option in classOptions" :key="option.value" :value="option.value">
              <div class="status-text" v-if="option.value == record.feedback_category_id">{{ option.label }}</div>
            </template>
          </template>
          <template v-if="column.dataIndex == 'operation'">
            <a-button type="link" class="link" @click="handleDetail(record)">
              查看
            </a-button>
            <a-button type="link" class="link" @click="handleDelete(record)" v-if="!record.deleted"
              style="color: #ff4d4f;">
              删除
            </a-button>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script setup>
import { ref, computed, h, onMounted, onUnmounted } from "vue";
import {
  SearchOutlined,
  ReloadOutlined,
  DownOutlined,
  UpOutlined,
} from "@ant-design/icons-vue";
import { Modal, message } from 'ant-design-vue';

import { useRouter } from "vue-router";
import { useGlobalStore } from "@/store/modules/global";
import Feedback from '@/api/Feedback.ts'
import apiClient from '@/api'
const store = useGlobalStore();
const router = useRouter();
const labelCol = { style: { width: "80px" } };

const classOptions = ref([])

const formState = ref({
  name: "",
  account: "",
  feedback_status_id: undefined,
  createTime: [],
  custorm: [],
  login_name: '',
  feedback_category_idArray: [],

});
const resetForm = async () => {
  formState.value = {
    name: "",
    account: "",
    feedback_status_id: undefined,
    createTime: [],
    custorm: [],
    login_name: '',
    feedback_category_idArray: [],

  };
  // 重置问题分类选择

  // 重置分页到第一页
  current.value = 1;
  // 重新获取数据
  await getData();
};
const windowWidth = ref(window.innerWidth);
const expand = ref(true);
onMounted(async () => {
  windowWidth.value = window.innerWidth;
  if (windowWidth.value > 768) {
    expand.value = true;
  } else {
    expand.value = false;
  }
  window.addEventListener("resize", () => {
    windowWidth.value = window.innerWidth;
    if (windowWidth.value > 768) {
      expand.value = true;
    } else {
      expand.value = false;
    }
  });
  await getData();
  await loadClassOptions();
});

// 加载问题分类选项
const loadClassOptions = async () => {
  try {
    const response = await apiClient.apiFeedbackCategoryOptionsPost({ keyWords: '' })
    if (response.data) {
      classOptions.value = response.data.map(item => ({
        label: item.text || item.label,
        value: item.value
      }))
    }
  } catch (error) {
    console.error('加载问题分类选项失败:', error)
    // 如果接口调用失败，使用默认选项
    classOptions.value = [
      { label: '技术问题', value: 1 },
      { label: '账户问题', value: 2 },
      { label: '功能建议', value: 3 },
      { label: '其他', value: 4 }
    ]
  }
}
const getData = async () => {
  console.log(formState.value.feedback_category_idArray, 'feedback_category_idArray.value')
  try {
    // 构建查询参数的 args 对象
    const args = {
      current: current.value,
      pageSize: pageSize.value,
    };

    // 只有当数据存在时才添加对应的参数
    if (formState.value.name) {
      args.name = formState.value.name;
    }

    if (formState.value.login_name) {
      args.login_name = formState.value.login_name;
    }

    if (formState.value.feedback_status_id !== undefined) {
      args.feedback_status_id = formState.value.feedback_status_id;
    }

    if (formState.value.feedback_category_idArray && formState.value.feedback_category_idArray.length > 0) {
      args.feedback_category_idArray = formState.value.feedback_category_idArray;
    }

    // 处理时间范围参数
    if (formState.value.createTime && formState.value.createTime.length === 2) {
      args.create_dateRange = [
        formState.value.createTime[0]?.format('YYYY-MM-DD'),
        formState.value.createTime[1]?.format('YYYY-MM-DD')
      ];
    }

    // 按照要求的格式包装参数
    const params = {
      args: args
    };

    console.log('查询参数:', params);
    const res = await Feedback.PagedList(params);
    console.log(res, '获取反馈列表');

    // 假设API返回的数据结构为{ data: [], total: 0 }
    if (res && res.data) {
      tableData.value = res.data;
      total.value = res.total || 0;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    message.error('获取数据失败，请重试');
  }
}
onUnmounted(() => {
  window.removeEventListener("resize", () => { });
});

const onFinish = async (values) => {
  console.log("查询参数:", values);
  // 重置分页到第一页
  current.value = 1;
  // 执行查询
  await getData();
};
const tableData = ref([

]);

const columns = ref([
  {
    dataIndex: "user_name",
    title: "姓名",
    width: 100,
  },
  {
    dataIndex: "login_name",
    title: "账号",
    width: 160,
  },
  {
    dataIndex: "created",
    title: "反馈时间",
    width: 160,
  },
  {
    dataIndex: "feedback_category_id",
    title: "问题类型",
    width: 110,
  },
  {
    dataIndex: "description",
    title: "问题描述",
    width: 250,
  },
  {
    dataIndex: "files",
    title: "附件",
    width: 180,
  },
  {
    dataIndex: "status_name",
    title: "处理状态",
    width: 180,
  },
  {
    dataIndex: "operation",
    title: "操作",
    width: 150,
    align: "center",
    fixed: "right",
  },
]);

const onChange = async (page) => {
  console.log('分页变化:', page);
  current.value = page.current;
  pageSize.value = page.pageSize;
  // 分页变化时重新获取数据
  await getData();
};
const current = ref(1);
const pageSize = ref(10);
const total = ref(0);
const pagination = computed(() => ({
  position: ["bottomCenter"],
  total: total.value,
  current: current.value,
  pageSize: pageSize.value,
  showSizeChanger: true,
  size: "large",
  showTotal: (total) => `共 ${total} 条`,
}));

const handleAdd = () => {
  store.setSubTitle("新增反馈");
  router.push("senior-feedback-option");
};

const handleDetail = async (data) => {
  console.log(data, 'data')
  store.setSubTitle("查看反馈信息");

  try {
    // 调用FetchModel接口获取详细信息
    const res = await Feedback.FetchModel({ feedback_id: data.feedback_id });
    console.log('获取反馈详情', res);

    // 将反馈详情数据传递给详情页面
    router.push({
      path: "/senior-feedback-detail",
      query: {
        feedbackData: JSON.stringify(res.data || res)
      }
    });
  } catch (error) {
    console.error('获取反馈详情失败', error);
    // 如果获取详情失败，仍然跳转到详情页面，但不传递数据
    router.push({ path: "/senior-feedback-detail", params: { feedbackId: data.feedback_id } });
  }
};
const handleEdit = (data) => {
  console.log("编辑客户", data);
  store.setSubTitle("编辑客户账号");
  router.push("senior-account-option");
};

const handleDelete = async (data) => {
  try {
    // 使用 Modal.confirm 显示删除确认框
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条反馈吗？删除后不可恢复。',
      okText: '确认',
      cancelText: '取消',
      async onOk() {
        try {
          const res = await Feedback.Delete({ feedback_id: data.feedback_id });
          message.success('删除成功');
          // 删除成功后重新获取数据
          await getData();
        } catch (error) {
          message.error('删除失败');
          console.error('删除反馈失败', error);
        }
      }
    });
  } catch (error) {
    message.error('操作失败');
    console.error('删除操作失败', error);
  }
};
const handleExport = async () => {
  try {
    // 构建导出参数，使用当前搜索条件
    const exportParams = {
      current: current.value,
      pageSize: pageSize.value
    };

    // 只有当字段有值时才添加到参数中
    if (formState.value.name) {
      exportParams.name = formState.value.name;
      exportParams.login_name = formState.value.name;
    }
    if (formState.value.feedback_status_id !== undefined && formState.value.feedback_status_id !== null) {
      exportParams.feedback_status_id = parseInt(formState.value.feedback_status_id);
    }
    if (formState.value.feedback_category_idArray && formState.value.feedback_category_idArray.length > 0) {
      exportParams.feedback_category_idArray = formState.value.feedback_category_idArray;
    }
    if (formState.value.createTime && formState.value.createTime.length === 2) {
      exportParams.create_dateRange = formState.value.createTime;
    }

    console.log("导出参数:", exportParams);

    // 调用导出API
    const response = await Feedback.Export(exportParams);

    console.log("导出响应:", response);

    if (response && response.file) {
      const fileData = response.file;

      // 处理Base64编码的文件内容
      const base64Content = fileData.fileContents;
      const contentType = fileData.contentType || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      const fileName = fileData.fileDownloadName || '用户收藏仪器_导出.xlsx';

      try {
        // 将Base64字符串转换为二进制数据
        const binaryString = atob(base64Content);
        const bytes = new Uint8Array(binaryString.length);
        for (let i = 0; i < binaryString.length; i++) {
          bytes[i] = binaryString.charCodeAt(i);
        }

        // 创建Blob对象
        const blob = new Blob([bytes], { type: contentType });

        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;

        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        // 清理URL对象
        window.URL.revokeObjectURL(url);

        message.success("导出成功");
      } catch (decodeError) {
        console.error("文件解码失败:", decodeError);
        message.error("文件解码失败，请稍后重试");
      }
    } else {
      const errorMessage = response?.errors?.[0] || "导出失败";
      console.error("导出失败:", response);
      message.error(errorMessage);
    }
  } catch (error) {
    console.error("导出用户收藏仪器列表失败:", error);
    message.error("导出失败，请稍后重试");
  } finally {

  }
};

// 导入功能
const handleImport = async (file) => {
  try {
    // 检查文件类型
    const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      file.type === 'application/vnd.ms-excel';

    if (!isExcel) {
      message.error('只能上传 Excel 文件！');
      return false;
    }

    // 检查文件大小（限制为10MB）
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error('文件大小不能超过 10MB！');
      return false;
    }

    message.loading('正在导入数据...', 0);

    // 创建 FormData 对象
    const formData = new FormData();
    formData.append('file', file);

    // 使用Feedback.Import方法
    const res = await Feedback.Import(formData);

    message.destroy();

    if (res && res.success) {
      message.success(`导入成功，共导入 ${res.count || 0} 条数据`);
      // 重新获取数据
      await getData();
    } else {
      message.error(res?.message || '导入失败');
    }
  } catch (error) {
    message.destroy();
    message.error('导入失败');
    console.error('导入失败', error);
  }

  // 阻止默认上传行为
  return false;
};
</script>
<style lang="less" scoped>
.list-pages {
  height: 100%;
  padding: 0 16px;
  display: flex;
  flex-direction: column;

  .search-box {
    display: flex;
    align-items: center;
    padding: 18px 0;
    flex-wrap: wrap;
    border-bottom: 1px solid #e5e7eb;

    .search-select {
      width: 120px;
    }

    .line {
      width: 1px;
      height: 16px;
      margin: 0 12px;
      background: #bec4ca;

      @media screen and (max-width: 768px) {
        display: none;
      }
    }

    .search-input-box {
      flex: 1;
      display: flex;
      align-items: center;

      @media screen and (max-width: 768px) {
        width: 100%;
        margin-top: 16px;
        justify-content: space-between;
      }
    }

    .search-input {
      flex: 1;
    }

    .search-btn {
      width: 60px;
      height: 32px;
      background: #2776ff;
      border-radius: 4px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      font-size: 14px;
      color: #ffffff;
      text-align: center;
      line-height: 32px;
    }
  }

  .opt-button-box {
    padding: 16px 0;
    display: flex;
    align-items: center;

    .btn {
      display: flex;
      align-items: center;
      height: 32px;
      padding: 0 16px;
      border-radius: 4px;
      font-size: 14px;

      .icon {
        width: 16px;
        height: 16px;
        margin-right: 8px;
      }
    }
  }

  .table-wrapper {
    width: 100%;
    flex: 1;
    overflow: hidden;

    .table-box {
      height: 100%;
    }
  }

  .list-box {
    width: 100%;
    box-sizing: border-box;
    padding-top: 16px;
    overflow: auto;
    display: grid;
    gap: 16px;
    margin: 0 auto;
    grid-template-columns: repeat(auto-fill, minmax(261px, 1fr));
    justify-content: space-between;

    .list-item {
      width: 261px;
      background: #ffffff;
      border: 1px solid #e6ebf1;
      border-radius: 8px;
      box-sizing: border-box;
      padding: 8px;
      margin: auto;
      position: relative;
      cursor: pointer;

      &:hover {
        border: 1px solid #2776ff;
        box-shadow: 12px 12px 12px 0px rgba(39, 118, 255, 0.1);
      }

      .item-collect {
        position: absolute;
        top: 0;
        right: 0;
        cursor: pointer;
        width: 32px;
        height: 32px;
        background: rgba(0, 0, 0, 0.4) url(@/assets/icon-collet.png) no-repeat center center;
        border-radius: 0 8px 0 12px;

        &.cur {
          background: #ffffff url(@/assets/icon-collet-cur.png) no-repeat center center;
          border-radius: 0 8px 0 12px;
        }
      }

      .list-img {
        width: 245px;
        height: 249px;
        background: #f3f3f3;
        border: 1px solid #e6ebf1;
        border-radius: 8px;
        box-sizing: border-box;

        img {
          width: 100%;
          height: 100%;
          border-radius: 8px;
        }
      }

      .list-content {
        padding: 14px 0 6px;
        display: flex;
        flex-direction: column;

        .content-title {
          font-family: PingFangSC-Medium;
          font-weight: 500;
          font-size: 16px;
          color: #31323a;
          margin-bottom: 10px;
          line-height: 24px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .content-col {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .col-user {
            display: flex;
            align-items: center;

            .user-img {
              width: 26px;
              height: 26px;
              border-radius: 50%;
            }

            .user-name {
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 12px;
              color: #262626;
              line-height: 16px;
              text-align: left;
              font-style: normal;
            }
          }

          .col-date {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 12px;
            color: #8c8c8c;
            line-height: 16px;
            text-align: center;
            font-style: normal;
          }
        }
      }
    }
  }

  .pagination-box {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
